<template>
    <div :style="containerStyle" class="invest-table-container" :key="fullscreen">

        <el-row class="select-list" :style="{ height: headerHeight(models.headCode.length) }" v-if="models.headCode && formData.head">
            <h5 class="textCenter" style="top:-25px;position: relative;" >{{ models.title }}</h5>
            <template v-if="models.headCode && models.headCode.length > 0">
                <div :style="{ position: 'relative', top: '-45px', height: headerItemHeight(models.headCode.length) }">
                    <el-row style="width: 100vh;height: 24px" v-for="(code, index) in models.headCode" :key="index">
                        <el-input v-model="formData.head[code.name]" :id="code.name" :placeholder="code.label" :key="code.name"
                            @input="updateHeadField(code.name, $event)"
                            class="transparentInput" style="width:100%;margin: 0px;" size="small">
                            <template slot="prepend"><span class="inputLabel">{{ code.label }} ：</span></template>
                        </el-input>
                    </el-row>
                </div>
            </template>
        </el-row>
        <el-table :data="models.common" ref="dataTable"  style="width: 100%; min-height:150px;" :height="tableHeight"
            :header-cell-style="{ background: '#F2F6FC' }">
            <el-table-column prop="code" label="代码" min-width="80" align="center">
                <template slot-scope="scope">
                    <span class="textCenter">
                        {{ scope.row.code }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="指标名称" min-width="160" header-align="left" align="left">
                <template slot-scope="scope">
                    <span v-if="scope.row.code == '——'">
                        <h4>{{ scope.row.name }}</h4>
                    </span>
                    <span v-else type="success">{{ scope.row.name }}</span>
                    <el-tooltip v-if="scope.row.descText" class="item" effect="dark" :content="scope.row.descText"
                        placement="left-start">
                        <i class="el-icon-question" style="color:#C0C4CC"></i>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="investData" class="inputLable" label="普查数据" min-width="240" align="left">
                <template slot-scope="scope">
                    <span v-if="scope.row.contentType === '-'" class="textCenter">{{ scope.row.updateText
                        }}</span>
                    <span v-else-if="scope.row.contentType === '0'">
                        <el-input :disabled="scope.row.disabled" v-model="formData.code[scope.row.inputCode]"
                            :value="String(formData.code[scope.row.inputCode] || '')"
                             @input="updateInputField(scope.row.inputCode, $event)"
                            :placeholder="scope.row.name" @change="changeCode(scope.row.inputCode, $event)"
                            size="small" />
                    </span>
                    <div v-else-if="scope.row.contentType === '1'" class="inputLabel">
                        <el-checkbox-group v-model="formData.code[scope.row.inputCode]" :max="1" size="mini"
                            @change="changeCode(scope.row.inputCode, $event)">
                            <el-checkbox v-for="city in scope.row.investCategory" :label="city" :key="city">{{ city
                                }}</el-checkbox>

                        </el-checkbox-group>
                        <el-input
                            v-show="hasOtherItem(scope.row.investCategory) && hasOtherItem(formData.code[scope.row.inputCode])"
                            v-model="formData.codeExt[scope.row.inputCode]" :key="`ext-${scope.row.inputCode}`" autoComplete :placeholder="scope.row.name"
                            size="small" />

                    </div>
                    <div v-else-if="scope.row.contentType === '2'" class="inputLabel">
                        <el-checkbox-group v-model="formData.code[scope.row.inputCode]" size="mini"
                            @change="changeCode(scope.row.inputCode, $event)">
                            <el-checkbox v-for="city in scope.row.investCategory" :label="city" :key="city">{{ city
                                }}</el-checkbox>

                        </el-checkbox-group>
                        <el-input
                            v-show="hasOtherItem(scope.row.investCategory) && hasOtherItem(formData.code[scope.row.inputCode])"
                            v-model="formData.codeExt[scope.row.inputCode]" :placeholder="scope.row.name"
                            size="small" />
                    </div>
                    <div v-show="validateData[scope.row.inputCode]" class="error-message">{{
                        validateData[scope.row.inputCode] }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="unit" label="计量单位" width="min-width" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.unit }}</span>
                </template>
            </el-table-column>
        </el-table>
    
        <el-row  v-if="models.endCode && models.endCode.length > 0" class="bottom-list" style="height: auto; padding: 0px;background-color: white;">
            
            <template v-for="(code, index) in sortedEndCodes">
                <el-col v-if="!isDescription(code.label)" :span="8" :key="index">
                    <!-- 日期类型 -->
                    <el-form>
                    <el-date-picker v-if="isDate(code.label)" v-model="formData.end[code.name]" type="date"
                        :placeholder="code.label" format="yyyy/MM/dd" value-format="yyyy/MM/dd" size="small"
                        class="w-full">
                        <template #prepend>
                            <span class="inputLabel">{{ code.label }}：</span>
                        </template>
                    </el-date-picker>
         
                    <!-- 手机号类型 -->
                    <el-form-item v-else-if="isPhone(code.label)"  :rules="rules.phoneRules">
                        <el-input v-model="formData.end[code.name]" :placeholder="code.label" size="small">
                            <template #prepend>
                                <span class="inputLabel">{{ code.label }}：</span>
                            </template>
                        </el-input>
                    </el-form-item>

                    <!-- 邮箱类型 -->
                    <el-form-item v-else-if="isEmail(code.label)" :rules="rules.emailRules">
                        <el-input v-model="formData.end[code.name]" :placeholder="code.label" size="small">
                            <template #prepend>
                                <span class="inputLabel">{{ code.label }}：</span>
                            </template>
                        </el-input>
                    </el-form-item>
                

                    <!-- 其他普通输入 -->
                    <el-input v-else v-model="formData.end[code.name]" :placeholder="code.label" size="small">
                        <template #prepend>
                            <span class="inputLabel">{{ code.label }}：</span>
                        </template>
                    </el-input>
                </el-form>
                </el-col>
            </template>
            <template v-for="(code, index) in sortedEndCodes">
            <!-- 单独处理填写说明 -->
            <el-col  v-if="isDescription(code.label)" :key="'desc-' + index"
                :span="22"
                class="mt-4" 
                >
                <el-input v-model="formData.end[code.name]" type="textarea" style="margin-left: 20px;margin-bottom: 10px;" :rows="3" :placeholder="code.label"
                    size="small">
                    <template #prepend>
                        <span class="inputLabel">{{ code.label }}：</span>
                    </template>
                </el-input>
            </el-col>
        </template>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
@Component
export default class InvestTable extends Vue {
    @Prop() private validateData: any;
    @Prop() formData;
    @Prop() private models: any;
    @Prop({
        default: () => '100vh'
    }) private tableHeight!: any;

    @Prop()
    private fullscreen: any = false;
 

    rules: any = {
        phoneRules: [
            {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入有效的手机号码',
                trigger: 'blur'
            }
        ],
        // 邮箱校验规则（使用Element内置格式）
        emailRules: [
            { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
        ]
    }

    get headerItemHeight() {
        return function (len) {
            return ((len - 1) * 24) + "px";
        }
    }

    get sortedEndCodes() {
        return [...this.models.endCode].sort((a, b) => {
            const aIsDesc = this.isDescription(a.label);
            const bIsDesc = this.isDescription(b.label);
            return aIsDesc ? 1 : bIsDesc ? -1 : 0;
        });
    }

    get headerHeight() {
        return function (len) {
            return ((len + 1) * 24) + "px";
        }
    }

    private updateHeadField(fieldName: string, value: any) {
        // 确保值转换为字符串
        const safeValue = Array.isArray(value) ? value.join(', ') : String(value);
        this.$set(this.formData.head, fieldName, safeValue);
    }

     // 添加新方法
  updateInputField(inputCode, value) {
    this.$set(this.formData.code, inputCode, value);
  }

  changeCode(inputCode, value) {
   
    // 获取当前行的 contentType
    let contentType = '0';
    if (this.models.common) {
      const row = this.models.common.find(item => item.inputCode === inputCode);
      if (row) contentType = row.contentType;
    }


    // 根据 contentType 转换值类型
    if (contentType === '0') {
      const safeValue = Array.isArray(value) ? value.join(',') : String(value);
      this.$set(this.formData.code, inputCode, safeValue);
    } else if (contentType === '1' || contentType === '2') {

        const arrayValue = Array.isArray(value) ? value : [value];
        this.$set(this.formData.code, inputCode, arrayValue);
      
        // 处理"其它"选项
        if (this.hasOtherItem(arrayValue)) {
         
            // 初始化或保留已有的其它输入值
            if (this.formData.codeExt[inputCode] === undefined) {
                this.$set(this.formData.codeExt, inputCode, '');
            }
        } else {
            // 清除不再需要的其它输入
            this.$set(this.formData.codeExt, inputCode, undefined);
        }
    }
   
  }


    /**
     * 判断给定的标签是否包含“日期”字样
     *
     * @param {string} label - 需要判断的标签
     * @returns {boolean} 如果标签中包含“日期”，则返回 true；否则返回 false
     */
    isDate(label) {
        return label.includes('日期');
    }
    isPhone(label) {
        return label.includes('电话') || label.includes('手机');
    }
    isEmail(label) {
        return label.includes('邮箱');
    }
    isDescription(label) {
        return label.includes('填写说明');
    }


   hasOtherItem(value) {
        if(!value) return false;
        const flag =  value.some(v => v.includes('其它') || v.includes('其他'));

        return flag;
    }

    options: any = {
        numberTitle: ['个', '间', '人', '册', '件', '套', '席', '人次', '册/件/套', '件/套', '人次', '万人']

    }

    get containerStyle() {
        console.log('是否全屏' + this.fullscreen)
          return {
              height: this.fullscreen ? '100vh' : 'calc(100vh - 120px)',
              minHeight: '0'
          };
    }
}

</script>
<style scoped>
.invest-table-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    min-height: 0;
}
.error-message {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
}

.inputLabel {
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.bottom-list{
    margin: 0px;
    padding: 0px;
}
</style>